<?php

namespace addons\notice\library\server;

use addons\notice\library\ToData;
use app\admin\model\bot\Bot;
use hnh\custom\Log;
use Telegram\Bot\Api;

class Telegram
{
    // 获取通知数据
    public function getNoticeData($event, $template, $params)
    {

        // 接收信息
        $toData = [
            'to_id' => [],
            'email' => [],
            // 默认字段
            'default_field' => [],

        ];
        $toData = ToData::get($event, $template, $params);
        $botModel = new Bot();

        $bot = $botModel->where('status', 'normal')->field('token,buttons,button_column')->find();
        $token = $bot['token'];


        // 默认字段
        $params = array_merge($params, $toData['default_field']);
        $content = self::formatParams($template['content'], $params);


        $to_id = $toData['to_id'];
        $telegrams = $toData['telegram'];
        try {
            $response = null;
            $telegram = new Api($token);
            //region 处理按钮
            $inline_keyboard = $botModel->getButtons($bot['buttons'], $bot['button_column']);
            $keyboard['inline_keyboard'] = $inline_keyboard;
            $reply_markup = $telegram->inlineKeyboardMarkup($keyboard);
            //endregion
            // 发送电报通知
            foreach ($telegrams as $chat_id) {

                $response = $telegram->sendMessage([
                    'chat_id' => $chat_id,
                    'text' => $content,
                    "parse_mode" => "Markdown",
                    'reply_markup' => $reply_markup
                ]);

            }
            if (empty($response->getMessageId())) {
                // 记录日志
                $logData = [
                    'name' => $event['name'] . '-Telegram发送失败',
                    'event' => $event->toArray(),
                    'params' => $params,
                    'error' => '发送失败'
                ];
                Log::error($logData);
            }
        } catch (\Exception $e) {
            // 记录日志
            $logData = [
                'name' => $event['name'] . '-Telegram发送失败',
                'event' => $event->toArray(),
                'params' => $params,
            ];
            Log::catch('Telegram发送失败', $e, $logData);
        }

        return [
            'to_id' => $to_id,
            'content' => $content,
        ];
    }


    // 格式化模板数据
    public static function formatParams($content, $params)
    {
        if (preg_match_all("/(?<=({{)).+?(?=}})/", $content, $matches)) {
            foreach ($matches[0] as $k => $field) {
                $fieldVal = $params[$field] ?? null;
                if ($fieldVal !== null) {
                    $content = str_replace("{{" . $field . "}}", $fieldVal, $content);
                }
            }
        }

        return $content;
    }
}